<template>
	<div ref="el" class="h-8 flex justify-between gap-2 text-white app-font-bold">
		<div
			v-for="item in selections"
			:key="item.id"
			class="flex-1 h-full rounded-lg pl-[10px] pr-1 flex justify-between items-center cursor-pointer app-bg-react"
			:class="isSelect(item.id) ? 'bg-primary' : 'bg-white-200'"
			@click="onSelect(item.id)">
			<div>{{ getBetName(item) }}</div>
			<betting-odds-animate :value="item.displayOdds" :trend="item.trend" />
		</div>
	</div>
</template>

<script lang="ts" setup>
import { PropType, computed, ref } from 'vue'
import { BettingOddsAnimate } from '@/components/betting'
import { Match, Selection, BetslipItemStatus } from '@/types'
import { BettingType, BettingMethod } from '@/enums'
import { getBettingCode, t, RegBettingPoints } from '@/utils'
import { useBetslipStore } from '@/store'

const props = defineProps({
	data: {
		type: Object as PropType<Match>,
		required: true
	}
})

const el = ref<HTMLElement | null>(null)

const useBetslip = useBetslipStore()

const selections = computed(() => {
	const market = props.data.markets[0]
	if (market) {
		if (market.marketTypeCate === BettingType.moneyline) {
			return market.selections.slice().sort((a, b) => a.side - b.side)
		} else {
			return market.selections
		}
	}
	return []
})

const getBetName = (data: Selection) => {
	const type = data.id.substring(1, 3)
	const { betslipLine, side } = data
	if (type === getBettingCode(BettingType.moneyline)) {
		if (side === 1) {
			return t('bettingItem.home')
		} else if (side === 3) {
			return t('bettingItem.away')
		} else {
			return t('bettingItem.draw')
		}
	} else if (type === getBettingCode(BettingType.handicap)) {
		const { points } = data
		let pointsStr: string = '' + points
		if (points && points !== 0) {
			pointsStr = points > 0 ? ' +' + points : ' ' + points
		}
		if (side === 1) {
			return t('bettingItem.home') + ' ' + pointsStr
		} else {
			return t('bettingItem.away') + ' ' + pointsStr
		}
	} else if ('points' in data) {
		const pointInx = betslipLine.search(RegBettingPoints)
		if (pointInx > -1 && data.points && !isNaN(data.points)) {
			return betslipLine.substring(0, pointInx + 1) + ' ' + data.points
		}
	}
	return betslipLine
}

const isSelect = (id: string) => useBetslip.isInBetslip(id)

const onSelect = (id: string) => {
	useBetslip.select(
		{
			id: id,
			marketId: props.data.markets[0].marketId,
			eventId: props.data.eventId,
			amount: 0,
			status: BetslipItemStatus.none,
			type: BettingMethod.single
		},
		el.value?.getBoundingClientRect()
	)
}
</script>
